﻿namespace Blaze.Editor.Analysing
{
    using System.Collections.Generic;
    using UnityEditor;

    /// <summary>
    /// 用于分析资源的引用情况。
    /// </summary>
    public static class ReferenceAnalysor
    {
        /// <summary>
        /// 获取一个值，表示是否已有统计数据。
        /// </summary>
        public static bool Available { get; private set; }

        /// <summary>
        /// 获取指定的资源引用计数。
        /// </summary>
        /// <param name="assetPath">资源路径</param>
        public static int GetReferenceCount(string assetPath)
        {
            int ret;
            if (mReferenceCountersByAssetPath.TryGetValue(assetPath, out ret))
                return ret;
            return 0;
        }

        [MenuItem("Blaze/分析/资源引用", false, BlazeEditorMenu.Priority.Panels + 1)]
        public static void Start()
        {
            mReferenceCountersByAssetPath.Clear();
            var assetPaths = AssetDatabase.GetAllAssetPaths();
            for (var i = 0; i < assetPaths.Length; i++)
            {
                var assetPath = assetPaths[i];
                if (EditorUtility.DisplayCancelableProgressBar("正在分析", assetPath, (float) i/assetPaths.Length))
                {
                    EditorUtility.ClearProgressBar();
                    return;
                }
                var dependencies = AssetDatabase.GetDependencies(assetPath, false);
                for (var j = 0; j < dependencies.Length; j++)
                    increase(dependencies[j]);
            }
            EditorUtility.ClearProgressBar();
            Available = true;
        }

        private static void increase(string assetPath)
        {
            if (mReferenceCountersByAssetPath.ContainsKey(assetPath))
                mReferenceCountersByAssetPath[assetPath]++;
            else
                mReferenceCountersByAssetPath[assetPath] = 1;
        }

        private static readonly Dictionary<string, int> mReferenceCountersByAssetPath = new Dictionary<string, int>();
    }
}